package com.app.core.web.filter;

import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.StringUtils;

import com.app.core.common.AppCons;
import com.app.core.session.UserSession;
import com.app.core.web.context.RequestContext;
import com.app.core.web.util.AppContextUtil;

/**
 * request 全局请求变量公共设置，方便后面的获取调用
 * 
 * @since v#{version}
 * @author zhangxf
 * @created 2015年10月24日 下午10:22:45
 */
public class RequestContextFilter implements Filter {

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain chain)
        throws IOException, ServletException {
        try {
            // HttpServletResponse response = (HttpServletResponse) servletResponse;
            HttpServletRequest request = (HttpServletRequest) servletRequest;
            String contextPath = request.getContextPath();
            String requestURI = request.getRequestURI();
            requestURI = requestURI.substring(contextPath.length(), requestURI.length());
            UserSession userSession = null;

            RequestContext.setRequest(request);
            RequestContext.setResponse((HttpServletResponse) servletResponse);

            /*
             * 客户端
             */
            if (requestURI.startsWith("/app/")) {
                // 获取用户登录token
                Object tokenObj = request.getParameter("token");
                if (tokenObj == null) {
                    tokenObj = request.getAttribute("token");
                }

                if (tokenObj != null && StringUtils.isNoneBlank(tokenObj.toString())) {
                    userSession = (UserSession) AppContextUtil.getSessionValue(tokenObj.toString());
                }
            }

            if (userSession != null) {
                RequestContext.setUserSession(userSession);
                RequestContext.setLoginUserId(userSession.getUserId());
                RequestContext.setLoginUserName(userSession.getLoginName());
                RequestContext.setUserId(userSession.getUserId());

                request.setAttribute("userSession", userSession);
                AppContextUtil.setSessionValue(userSession.getSessionId(), userSession, AppCons.USER_SESSION_TIMEOUT);
            }

            chain.doFilter(request, servletResponse);
        } finally {
            RequestContext.clearVariable();
        }
    }

    @Override
    public void destroy() {

    }
}
